<?php namespace App\Core\Service\Services;

use DB;
use App\Core\Exceptions\InputError;

trait Deleter{
    
    public $deleteModels = [];
    
    public function delete(){
        try {
            $this->getRepository()->addCriteria($this->getIndexCriteria());
            $this->fireEvent('deleteBeforeSave');
            $model = $this->deleteDropData();
            $this->fireEvent('deleteAfterSave', $model);
            return $this->success();
		} catch (\Exception $ex) {
            if($ex instanceof InputError){
                return $this->inputError($ex->getMessage());
            }
			return $this->sysError($ex);
		}
    }
    
    public function multiDelete(){
        try {
            $this->getRepository()->addCriteria($this->getIndexesCriteria());
            $this->fireEvent('deleteBeforeSave');
            $this->deleteDropData();
            $this->fireEvent('deleteAfterSave');
            return $this->success();
		} catch (\Exception $ex) {
            if($ex instanceof InputError){
                return $this->inputError($ex->getMessage());
            }
            return $this->sysError($ex);
		}
    }
    
    protected function deleteDropData(){
        DB::beginTransaction();
        try {
            $this->fireEvent('deleteSaving');
            $this->deleteModels = $this->getRepository()->delete();
            $this->fireEvent('deleteSaved');
            DB::commit();
		} catch (\Exception $ex) {
            DB::rollBack();
			throw $ex;
        }
    }
}